/**
 * LY.com Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package quorum.test;

import quorum.DataWrapper;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author bixiao.wang
 * @version $Id: MockNodeServer, v 0.1 2021/9/18 17:32 bixiao.wang Exp $
 */
public class MockNodeServer {

    // 模拟本地执行，
    private Map<String, TreeMap<Long, DataWrapper>> store = new HashMap<>();

    public boolean write(String key, DataWrapper dataWrapper) {
        if (!store.containsKey(key)) {
            store.put(key, new TreeMap<>());
        }
        store.get(key).put(dataWrapper.getVersion(), dataWrapper);
        return true;
    }

    public DataWrapper read(String key) {
        if (!store.containsKey(store)) {
            return null;
        }
        TreeMap<Long, DataWrapper> m = store.get(key);
        Map.Entry<Long, DataWrapper> last = m.lastEntry();
        if (last == null) {
            return null;
        }
        return last.getValue();
    }

    public boolean delete(String key, Long version) {
        if (store.containsKey(key)) {
            store.get(key).remove(version);
        }
        return true;
    }

    public boolean delete(String key) {
        store.remove(key);
        return true;
    }
}
